using Digitalmes.Domain.Entities.Mes.Productions;

namespace Digitalmes.Application.Mes.Traceability.Products.Queries;

/// <summary>
/// 查询工艺步骤下所有的工步及其过程数据命令。
/// </summary>
/// <param name="StepExecutionId">工艺步骤执行记录 Id</param>
public sealed record GetStepProcessDataQuery(long StepExecutionId) : IRequest<IResult<List<ProdStepTaskExecutionDto>>>;

internal sealed class GetStepProcessDataQueryHandler(IRepository<ProdStepExecution> stepExecutionRepo,
    IRepository<ProdStepTaskExecution> stepTaskExecutionRepo) : IRequestHandler<GetStepProcessDataQuery, IResult<List<ProdStepTaskExecutionDto>>>
{
    public async Task<IResult<List<ProdStepTaskExecutionDto>>> Handle(GetStepProcessDataQuery request, CancellationToken cancellationToken)
    {
        var stepExecution = await stepExecutionRepo.GetByIdAsync(request.StepExecutionId, cancellationToken);
        if (stepExecution == null)
        {
            return Result.From(new List<ProdStepTaskExecutionDto>());
        }

        var stepTaskExecution = await stepTaskExecutionRepo.AsQueryable()
            .Includes(m => m.Data)
            .Where(m => m.InboundId == stepExecution.InboundId && m.StepId == stepExecution.StepId)
            .ToListAsync(cancellationToken);
        return Result.From(stepTaskExecution.Adapt<List<ProdStepTaskExecutionDto>>());
    }
}
